package th.stripes.services;

import able.stripes.AbleActionBean;
import th.stripes.BaseActionBean;
import able.stripes.JSP;
import com.google.inject.Inject;
import com.oas.thit._this.flight.xsd.FlightScheduleResponseBody;
import com.oas.thit._this.hajj.xsd.HajjResponseBody;
import com.oas.thit._this.profile.depositor.xsd.DepositorProfileResponseBody;
import com.oas.thit._this.xsd.THISBaseDataElementBody;
import com.oas.thit.hajj.groupslip.xsd.GroupSlipResponseBody;
import com.oas.thit.hajj.groupslip.xsd.GroupSlipResponseLineItem;
import com.oas.thit.hajj.hjcheck.xsd.HjCheckRequestBody;
import com.oas.thit.hajj.hjcheck.xsd.HjCheckResponseBody;
import com.oas.thit.hajj.query.xsd.RegistrationQueryRequestBody;
import com.oas.thit.hajj.query.xsd.RegistrationQueryResponseBody;
import com.oas.thit.hajj.xsd.RequestBody;
import com.oas.thit.xmlmessage.xsd.Header;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import javax.xml.bind.JAXBElement;
import net.sourceforge.stripes.action.HandlesEvent;
import net.sourceforge.stripes.action.Resolution;
import org.apache.log4j.Logger;
import th.config.ableContextListener;
import th.dao.KodBandarDAO;
import th.dao.KodHubunganDAO;
import th.dao.KodJantinaDAO;
import th.dao.KodKahwinDAO;
import th.dao.KodNegeriDAO;
import th.dao.KodPekerjaanDAO;
import th.dao.KodSektorPekerjaanDAO;
import th.dao.KodStatusDAO;
import th.dao.KodStatusHajiDAO;
import th.dao.KodTahapPengajianDAO;
import th.dao.KodUrusanDAO;
import th.dao.KodWarganegaraDAO;
import th.dao.PoskodDAO;
import th.dao.PusatKosDAO;
import th.dao.THISutilDAO;
import th.manager.HajjManager;
import th.manager.SejarahTransaksiManager;
import th.model.Deposit;
import th.model.Haji;
import th.model.Pengguna;
import th.model.Poskod;
import th.model.SejarahTransaksi;
import th.model.SuratPenerbanganJH;
import th.stripes.action.HajiActionBean;
import th.stripes.action.DepositActionBean;
import th.stripes.config.AuthRequired;
import th.stripes.util.AccCheckUtil;
import th.stripes.webservice.WebServiceUtil;
import th.manager.ResponseManager;
import th.model.InfoAudit;
import th.model.KodStatus;
import th.model.PermohonanMaklumat;
import th.model.PermohonanMaklumatKeluarga;
import th.model.SlipPendaftaran;
import th.model.THISutil;
import th.stripes.Configuration;
import th.stripes.util.DateFormatDetector;
import th.stripes.util.ListUtil;
import th.stripes.config.ableActionBeanContext;

    
    
/*
 *
 * @author yogendra
 */

public class HajiService extends BaseActionBean {

    private static String SUCCESSFUL = "0000";
    private static String ACCEPTED = "6000";
    private static String DECLINED = "6301";
    private static String CLOSED = "6300";
    private static String DECLINED_G = "6200";
    private static String SYSTEM_ERROR = "9999";   
    private static String INVALID_ACC_IC = "9000"; 
    private static String NO_HAJJ_OFR_RECORD = "7000";
    private static String NO_FLIGHT_SCH_RECORD = "7000";
    private static String ACCOUNT_ALREADY_REGISTRED = "7000";
    private static String UNSUCCESSFULL = "1000";
    
    private static String HAJ_ENQ_MSG_ID = "TPHOFRCKWD01";
    private static final String BAL_ENQ_MSG_ID = "TPBALENQWD01";
    private static String HEADER_ID_HAJ_OFFER_CHECK = "THSHOCK";
    private static String HAJ_CHK_MSG_ID = "TPHAJCHKWD01";    
    private static String HEADER_ID_HAJ_REGISTRATION_CHECK = "THSHCHK";
    private static String FLT_SCH_MSG_ID = "TPHJFLSCWD01"; 
    private static String HEADER_ID_HAJ_FLIGHT_SCH = "THSHFSC";
    private static String OFF_LTR_MSG_ID = "TPHOFRLTWD01";    
    private static String HEADER_ID_HAJ_OFFER_LTR = "THSHOLT";
    private static String HAJ_SLIP_MSG_ID = "TPHJSLIPWD01"; 
    private static String PROFILE_ENQ_MSG_ID = "TPDPPROFWD01";
    private static String HEADER_ID_HAJ_SLIP_GROUP = "THSHSLP";
    private static String HAJ_REG_QUERY_MSG_ID = "TPHAJREGWD01";  
    private static String HEADER_ID_HAJ_REGISTRATION_QUERY = "THSHQRY";
    private static String HAJ_REG_MSG_ID = "TPHAJREGWD02";  
    private static String HEADER_ID_HAJ_REGISTRATION = "THSHREG";
    private static String HEADER_ID_PROFILE_ENQUIRY = "THSDPQR";
    private static final String HEADER_ID_BALANCE_ENQUIRY = "THSBENQ";
    
    
    private static String KOD_URUSAN_DAFTAR = "01";
    private static String KOD_URUSAN_JAWAB = "02";
    private static String KOD_STATUS_TERIMA= "01";
    private static String KOD_STATUS_TOLAK = "02";
    private static String STATUS_TAMBAHAN_WUJUD = "A";
    private static String STATUS_TAMBAHAN_CIPTA = "C";
    private static String STATUS_TAMBAHAN_UBAH = "U";
    private static String STATUS_CREATE = "V";
    private static String STATUS_ADD = "M";
    private static String STATUS_EXIST = "E";
    private static String TAWARAN_TIADA = "7770";
    private static String TAWARAN_TERIMA = "7771";
    private static String TAWARAN_TOLAK = "7772";
    private static String TAWARAN_BATAL = "7773";
    
    @Inject private KodUrusanDAO kodUrusanDAO;
    @Inject private HajjManager hajjManager;
    @Inject private KodNegeriDAO kodNegeriDAO;
    @Inject private PoskodDAO poskodDAO;
    @Inject private KodKahwinDAO kodKahwinDAO;
    @Inject private KodWarganegaraDAO kodWarganegaraDAO;
    @Inject private KodTahapPengajianDAO kodTahapPengajianDAO;
    @Inject private KodSektorPekerjaanDAO kodSektorPekerjaanDAO;
    @Inject private KodPekerjaanDAO kodPekerjaanDAO;
    @Inject private KodHubunganDAO kodHubunganDAO;
    @Inject private KodStatusDAO kodStatusDAO;
    @Inject private KodStatusHajiDAO kodStatusHajiDAO;
    @Inject private PusatKosDAO pusatKosDAO;
    @Inject private THISutilDAO tHISutilDAO;
    @Inject private KodBandarDAO kodBandarDAO;
    @Inject private ListUtil listUtil;
    @Inject private WebServiceUtil webUtil;
    @Inject private ResponseManager responseManager;
    @Inject private SejarahTransaksiManager sejarahTransaksiManager;
    @Inject private Configuration conf;    
    @Inject private KodJantinaDAO kodJantinaDAO;
    private static final Logger LOG = Logger.getLogger(DepositActionBean.class);
    
    
    private Deposit deposit;
    private Haji haji;
    private Pengguna pengguna;
    private String responseCode;
    private String idSessi;
  
//----------------------------------------------------PENDAFTARAN HAJI---------------------------------------------------------//   
    
    public String pendaftaranHaji(Haji haji, Pengguna pengguna, String responseCode, String idSessi ) {
        
        try {
            deposit = getProfileDeposit(haji.getNoAkaun(), haji.getNoKp());
        } catch (ParseException ex) {
            java.util.logging.Logger.getLogger(HajiActionBean.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        if (deposit != null) {
            
            AccCheckUtil checking = ableContextListener.newInstance(AccCheckUtil.class);
            deposit.setNoKpDari(haji.getNoKp());
            deposit.setNoAkaunDari(haji.getNoAkaun());
            boolean check = checking.checkAcc(deposit, pengguna);

            if (!check) {
                addSimpleError("" + responseManager.getResponseMessage("9000", PROFILE_ENQ_MSG_ID));
//                return new JSP("deposit/msg.jsp");
                return ("/");
            }
        } else {
            addSimpleError("" + responseManager.getResponseMessage("9000", PROFILE_ENQ_MSG_ID));
//                return new JSP("deposit/msg.jsp");
            
            return ("/");
        }
        
        //web service 
        try { // Call Web Service Operation
            com.oas.thit.hajj.services.HajjServices service = new com.oas.thit.hajj.services.HajjServices();
            com.oas.thit.hajj.services.HajjServicesPortType port = service.getHajjServicesHttpSoap11Endpoint();
            // TODO initialize WS operation arguments here
            com.oas.thit.hajj.query.xsd.RegistrationQueryRequest req = new com.oas.thit.hajj.query.xsd.RegistrationQueryRequest();
            
            com.oas.thit.hajj.query.xsd.ObjectFactory objFactory = new com.oas.thit.hajj.query.xsd.ObjectFactory();
            com.oas.thit.xmlmessage.xsd.ObjectFactory objHeader = new com.oas.thit.xmlmessage.xsd.ObjectFactory();
            Header reqHead = objHeader.createHeader();
            reqHead.setMsgId( objHeader.createHeaderMsgId(HAJ_REG_QUERY_MSG_ID));
            reqHead.setResponseCode( objHeader.createHeaderResponseCode(SUCCESSFUL) );            
            reqHead.setTxid(objHeader.createHeaderTxid( webUtil.getHeaderID(HAJ_REG_QUERY_MSG_ID, HEADER_ID_HAJ_REGISTRATION_QUERY) ));
            
            JAXBElement<Header> jReqHead = objHeader.createEventHeader(reqHead);
            req.setHeader(jReqHead); 
            
            RegistrationQueryRequestBody reqBody = objFactory.createRegistrationQueryRequestBody();
            reqBody.setTHAcctNo(objFactory.createRegistrationQueryRequestBodyTHAcctNo(haji.getNoAkaun()));
            reqBody.setTHICNo(objFactory.createRegistrationQueryRequestBodyTHICNo(haji.getNoKp()));
            
            JAXBElement<RegistrationQueryRequestBody> jReqBody =  objFactory.createRegistrationQueryRequestBody(reqBody);
            req.setBody(jReqBody);
            com.oas.thit.hajj.query.xsd.RegistrationQueryResponse result = port.registrationQueryRequest(req);
            
            Header header = result.getHeader().getValue();
            responseCode = header.getResponseCode().getValue(); 

            if (responseCode.equals(SUCCESSFUL)) {  
                
                RegistrationQueryResponseBody resp = result.getBody().getValue();                
//                PermohonanMaklumat permohonanMaklumat = hajjManager.findMohonMaklumatByNoAkaun(resp.getTHAcct().getValue().trim(), KOD_URUSAN_DAFTAR);              
                PermohonanMaklumat permohonanMaklumat = hajjManager.findMohonMaklumatByNoAkaun(haji.getNoAkaun().trim(), KOD_URUSAN_DAFTAR);    
                if(permohonanMaklumat!= null){
                    getContext().getRequest().getSession().setAttribute("hajjRegMemberList", permohonanMaklumat);
//                    return new JSP("haji/daftarhaji/pendaftaran_haji_simpan.jsp");
                    return("/haji/daftarhaji_detail.html");
                }else{
                    haji.setNoAkaun(resp.getTHAcct().getValue().trim());
                    haji.setNoKp(resp.getTHICNo().getValue().trim());
                    haji.setNama(resp.getTHName().getValue().trim());
                    haji.setNoTel1(resp.getTHPhoneH().getValue().trim());
                    haji.setNoTel2(resp.getTHPhoneOff().getValue().trim());
                    haji.setNoTel3(resp.getTHMobile().getValue().trim());
                    haji.setFax(resp.getTHFax().getValue().trim());
                    haji.setAlamat1(resp.getTHAddress1().getValue());
                    haji.setAlamat2(resp.getTHAddress2().getValue());
                    haji.setAlamat3(resp.getTHAddress3().getValue());
                    if(resp.getTHPoskod().getValue().substring(0, 5).trim().length()>0){
                        Poskod poskod = poskodDAO.findById(resp.getTHPoskod().getValue().substring(0, 5));
                        haji.setPoskod(poskod.getPoskod());
                        haji.setPoskodDeskripsi(poskod.getNama());
                        haji.setNegeri(poskod.getNegeri());
                    }
                    haji.setSenaraiNegeri(listUtil.getSenaraiNegeri());
                    haji.setSenaraikahwin(listUtil.getSenaraiPerkahwinan());
                    haji.setSenaraiHubungan(listUtil.getSenaraiHubungan());
                    haji.setSenaraipekerjaan(listUtil.getSenaraiPekerjaan());
                    haji.setPekerjaan(kodPekerjaanDAO.findById(resp.getTHEmploy().getValue())); 
                    haji.setSenaraiBandar(listUtil.getSenaraiBandar());
                    haji.setBandar(kodBandarDAO.findById(resp.getTHPlaceofBirth().getValue()));
//                    getContext().getRequest().getSession().setAttribute("haji",haji);
//                    return new JSP("haji/daftarhaji/pendaftaran_haji_detail.jsp");
                    return ("/haji/daftarhaji_detail.html");
                }    
            }else{
                addSimpleError("" + responseManager.getResponseMessage(responseCode, HAJ_REG_QUERY_MSG_ID));
            }            
        } catch (Exception ex) {
            LOG.error(ex);
            responseCode = SYSTEM_ERROR;
            addSimpleError("" + responseManager.getResponseMessage(responseCode, HAJ_REG_QUERY_MSG_ID));
         }
//        return new JSP("haji/msg.jsp");
        return responseCode;
    }
    

    public String savePendaftaranHaji (Haji haji, Pengguna pengguna, String responseCode, String idSessi ) {      
        pengguna = getContext().getCurrentUser();
        InfoAudit ia = new InfoAudit();
        ia.setDimasukOleh(pengguna);
        ia.setTarikhMasuk(new Date());
//        Haji hajiInSession = (Haji)getContext().getRequest().getSession().getAttribute("haji");
        getContext().getRequest().getSession().removeAttribute("haji");
        
        PermohonanMaklumat permohonanMaklumat = new PermohonanMaklumat();
        permohonanMaklumat.setUrusan(kodUrusanDAO.findById(KOD_URUSAN_DAFTAR));
        permohonanMaklumat.setNoAkaun(haji.getNoAkaun());
        permohonanMaklumat.setNoPengenalan(haji.getNoKp());
        permohonanMaklumat.setNama(haji.getNama());                      
        //permohonanMaklumat.setPendidikan(hajiInSession.getTahapPengajian());
        //permohonanMaklumat.setPekerjaan(hajiInSession.getPekerjaan());
        //permohonanMaklumat.setPerkahwinan(hajiInSession.getKahwin()); 
        //permohonanMaklumat.setWarganegara(hajiInSession.getWarganegara());        
        permohonanMaklumat.setAlamat1(haji.getAlamat1());
        permohonanMaklumat.setAlamat2(haji.getAlamat2());
        permohonanMaklumat.setAlamat3(haji.getAlamat3());
        permohonanMaklumat.setPoskod(haji.getPoskod());
        permohonanMaklumat.setNegeri(kodNegeriDAO.findById(haji.getNegeri().getCode()));
        permohonanMaklumat.setStatus(kodStatusDAO.findById("0000")); 
        permohonanMaklumat.setNoTel1(haji.getNoTel1());
        permohonanMaklumat.setNoTel2(haji.getNoTel2());
        permohonanMaklumat.setNoTel3(haji.getNoTel3());
        permohonanMaklumat.setNoFax(haji.getFax());
        permohonanMaklumat.setTempatLahir(haji.getBandar()); 
        permohonanMaklumat.setSektorPekerjaan(haji.getSektorPekerjaan());

        permohonanMaklumat.setInfoAudit(ia);
        
        hajjManager.saveMohonMaklumat(permohonanMaklumat);        
        permohonanMaklumat = hajjManager.findMohonMaklumatByNoAkaun(haji.getNoAkaun(), KOD_URUSAN_DAFTAR);
        haji.setMohonMaklumat(permohonanMaklumat);        
        
        getContext().getRequest().getSession().setAttribute("hajjRegMemberList", permohonanMaklumat);
//        return new JSP("haji/daftarhaji/pendaftaran_haji_simpan.jsp");
        return ("/");
    }
    

    public String showPopupTambahAhli(Haji haji, Pengguna pengguna, String responseCode, String idSessi ) {
       haji = new Haji();
       String noAkaunPenambah = getContext().getRequest().getParameter("noAkaunPenambah"); 
       haji.setNoAkaunPenambah(noAkaunPenambah);
//       return new JSP("/popup/haji/daftar/addnewmember.jsp");
       return("/");
    }
    

    public String showTambahDaftarAhli (Haji haji, Pengguna pengguna, String responseCode, String idSessi ) {        
        
        try { // Call Web Service Operation
            com.oas.thit.hajj.services.HajjServices service = new com.oas.thit.hajj.services.HajjServices();
            com.oas.thit.hajj.services.HajjServicesPortType port = service.getHajjServicesHttpSoap11Endpoint();
            // TODO initialize WS operation arguments here
            com.oas.thit.hajj.query.xsd.RegistrationQueryRequest req = new com.oas.thit.hajj.query.xsd.RegistrationQueryRequest();
            
            com.oas.thit.hajj.query.xsd.ObjectFactory objFactory = new com.oas.thit.hajj.query.xsd.ObjectFactory();
            com.oas.thit.xmlmessage.xsd.ObjectFactory objHeader = new com.oas.thit.xmlmessage.xsd.ObjectFactory();
            Header reqHead = objHeader.createHeader();
            reqHead.setMsgId( objHeader.createHeaderMsgId(HAJ_REG_QUERY_MSG_ID));
            reqHead.setResponseCode( objHeader.createHeaderResponseCode(SUCCESSFUL) );            
            reqHead.setTxid(objHeader.createHeaderTxid( webUtil.getHeaderID(HAJ_REG_QUERY_MSG_ID, HEADER_ID_HAJ_REGISTRATION_QUERY) ));
            
            JAXBElement<Header> jReqHead = objHeader.createEventHeader(reqHead);
            req.setHeader(jReqHead); 
            
            RegistrationQueryRequestBody reqBody = objFactory.createRegistrationQueryRequestBody();
            reqBody.setTHAcctNo(objFactory.createRegistrationQueryRequestBodyTHAcctNo(haji.getNoAkaun()));
            reqBody.setTHICNo(objFactory.createRegistrationQueryRequestBodyTHICNo(haji.getNoKp()));
            
            JAXBElement<RegistrationQueryRequestBody> jReqBody =  objFactory.createRegistrationQueryRequestBody(reqBody);
            req.setBody(jReqBody);
            com.oas.thit.hajj.query.xsd.RegistrationQueryResponse result = port.registrationQueryRequest(req);
            
            Header header = result.getHeader().getValue();
            responseCode = header.getResponseCode().getValue();
            
                if (responseCode.equals(SUCCESSFUL)) {                    
                    RegistrationQueryResponseBody resp = result.getBody().getValue();   
                    haji.setNoAkaun(resp.getTHAcct().getValue().trim());                    
                    haji.setNama(resp.getTHName().getValue());
                    haji.setNoTel1(resp.getTHPhoneH().getValue().trim());
                    haji.setNoTel2(resp.getTHPhoneOff().getValue().trim());
                    haji.setNoTel3(resp.getTHMobile().getValue().trim());
                    haji.setFax(resp.getTHFax().getValue().trim());
                    haji.setAlamat1(resp.getTHAddress1().getValue());
                    haji.setAlamat2(resp.getTHAddress2().getValue());
                    haji.setAlamat3(resp.getTHAddress3().getValue());
                    if(resp.getTHPoskod().getValue().substring(0, 5).trim().length()>0){
                        Poskod poskod = poskodDAO.findById(resp.getTHPoskod().getValue().substring(0, 5));
                        haji.setPoskod(poskod.getPoskod());
                        haji.setPoskodDeskripsi(poskod.getNama());
                        haji.setNegeri(poskod.getNegeri());
                    }
                    haji.setSenaraiNegeri(listUtil.getSenaraiNegeri());
                    haji.setSenaraikahwin(listUtil.getSenaraiPerkahwinan());
                    haji.setSenaraiHubungan(listUtil.getSenaraiHubungan());
                    haji.setSenaraipekerjaan(listUtil.getSenaraiPekerjaan());
                    haji.setPekerjaan(kodPekerjaanDAO.findById(resp.getTHEmploy().getValue()));                    
                    haji.setSenaraiBandar(listUtil.getSenaraiBandar());
                    haji.setBandar(kodBandarDAO.findById(resp.getTHPlaceofBirth().getValue()));
                    getContext().getRequest().getSession().setAttribute("haji",haji); 
//                    return new JSP("/popup/haji/daftar/listofmember.jsp");
                    return ("/");
                }
                addSimpleError("" + responseManager.getResponseMessage(responseCode, HAJ_REG_QUERY_MSG_ID));            
            } catch (Exception ex) {
            LOG.error(ex);
            responseCode = SYSTEM_ERROR;
            addSimpleError("" + responseManager.getResponseMessage(responseCode, HAJ_REG_QUERY_MSG_ID));  
        } 
//        return new JSP("/popup/haji/daftar/addnewmember.jsp");
        return("/");
    } 
    

    public String addNewMember (Haji haji, Pengguna pengguna, String responseCode, String idSessi ) { 
        
        pengguna = getContext().getCurrentUser();        
        InfoAudit ia = new InfoAudit();
        ia.setDimasukOleh(pengguna);
        ia.setTarikhMasuk(new Date()); 
        
        Haji hajiInSession = (Haji)getContext().getRequest().getSession().getAttribute("haji");
        getContext().getRequest().getSession().removeAttribute("haji");
        PermohonanMaklumat permohonanMaklumat = hajjManager.findMohonMaklumatByNoAkaun(haji.getNoAkaunPenambah(), KOD_URUSAN_DAFTAR);
        PermohonanMaklumatKeluarga permohonanMaklumtKeluarga = new PermohonanMaklumatKeluarga();        

        permohonanMaklumtKeluarga.setPermohonan(permohonanMaklumat);
        permohonanMaklumtKeluarga.setNoAkaun(hajiInSession.getNoAkaun());
        permohonanMaklumtKeluarga.setNoPengenalan(hajiInSession.getNoKp());
        permohonanMaklumtKeluarga.setNama(hajiInSession.getNama());
        permohonanMaklumtKeluarga.setAlamat1(hajiInSession.getAlamat1());
        permohonanMaklumtKeluarga.setAlamat2(hajiInSession.getAlamat2());
        permohonanMaklumtKeluarga.setAlamat3(hajiInSession.getAlamat3());
        permohonanMaklumtKeluarga.setPoskod(hajiInSession.getPoskod());
        permohonanMaklumtKeluarga.setNegeri(hajiInSession.getNegeri());
        permohonanMaklumtKeluarga.setNoTel1(hajiInSession.getNoTel1());
        permohonanMaklumtKeluarga.setNoTel2(hajiInSession.getNoTel2());
        permohonanMaklumtKeluarga.setNoTel3(hajiInSession.getNoTel3());
        
        permohonanMaklumtKeluarga.setStatushaji(hajiInSession.getStatusHaji());
        permohonanMaklumtKeluarga.setStatus(hajiInSession.getStatus());        
        permohonanMaklumtKeluarga.setHubungan(kodHubunganDAO.findById(haji.getHubungan().getKod()));
        
        permohonanMaklumtKeluarga.setInfoAudit(ia);        
       
        PermohonanMaklumatKeluarga returnMaklumatKeluarga = hajjManager.saveMohonMaklumatKeluarga(permohonanMaklumtKeluarga);       
        
       
        List maklumatKeluargaList;
        maklumatKeluargaList = permohonanMaklumat.getSenaraiMaklumatKeluarga();
        if(maklumatKeluargaList == null)
            maklumatKeluargaList = new ArrayList();
        maklumatKeluargaList.add(returnMaklumatKeluarga);        
        permohonanMaklumat.setSenaraiMaklumatKeluarga(maklumatKeluargaList); 
            
        getContext().getRequest().getSession().setAttribute("hajjRegMemberList", permohonanMaklumat);        
        //set Message if success, otherwise set message while throwing error
        getContext().getRequest().setAttribute("ReturnMessages", " Maklumat Anda Telah Berjaya Disimpan.");

//        return new JSP("/popup/haji/daftar/listofmember.jsp");    
        return ("/");
        
    }  
           
    //----------------------------------------------------SEMAK SLIP PENDAFTARAN---------------------------------------------------------//  
    
    public String semakPendaftaranHaji (Haji haji, Pengguna pengguna, String responseCode, String idSessi) {        
      
        DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");  
        
        try { // Call Web Service Operation
            com.oas.thit.hajj.services.HajjServices service = new com.oas.thit.hajj.services.HajjServices();
            com.oas.thit.hajj.services.HajjServicesPortType port = service.getHajjServicesHttpSoap11Endpoint();
            // TODO initialize WS operation arguments here
            com.oas.thit.hajj.hjcheck.xsd.HjCheckRequest req = new com.oas.thit.hajj.hjcheck.xsd.HjCheckRequest();
            
            com.oas.thit.hajj.hjcheck.xsd.ObjectFactory objFactory = new com.oas.thit.hajj.hjcheck.xsd.ObjectFactory();
            com.oas.thit.xmlmessage.xsd.ObjectFactory objHeader = new com.oas.thit.xmlmessage.xsd.ObjectFactory();
            Header reqHead = objHeader.createHeader();
            reqHead.setMsgId( objHeader.createHeaderMsgId(HAJ_CHK_MSG_ID));
            reqHead.setResponseCode( objHeader.createHeaderResponseCode(SUCCESSFUL) );            
            reqHead.setTxid(objHeader.createHeaderTxid( webUtil.getHeaderID(HAJ_CHK_MSG_ID, HEADER_ID_HAJ_REGISTRATION_CHECK) ));
           
            JAXBElement<Header> jReqHead = objHeader.createEventHeader(reqHead);
            req.setHeader(jReqHead); 

            HjCheckRequestBody reqBody = objFactory.createHjCheckRequestBody();
            reqBody.setTHAcct(objFactory.createHjCheckRequestBodyTHAcct(haji.getNoAkaun()));
            reqBody.setTHICNo(objFactory.createHjCheckRequestBodyTHICNo(haji.getNoKp()));
            
            JAXBElement<HjCheckRequestBody> jReqBody =  objFactory.createHjCheckRequestBody(reqBody);
            req.setBody(jReqBody);
            com.oas.thit.hajj.hjcheck.xsd.HjCheckResponse result = port.hjCheck(req);
            
            Header header = result.getHeader().getValue();
            responseCode = header.getResponseCode().getValue();
            if (responseCode.equals(SUCCESSFUL)) {
                HjCheckResponseBody resp = result.getBody().getValue();
                
                haji.setNoAkaun(resp.getTHAcct().getValue());
                haji.setNoRujukan(resp.getTHRefNo().getValue());
                haji.setNoDaftar(resp.getTHRegNo().getValue());
                haji.setNama(resp.getTHName().getValue());
                haji.setNoAkaun(resp.getTHAcct().getValue());
                haji.setNoKp(resp.getTHICNo().getValue());
                haji.setTahunPeruntukanHijrah(resp.getTHHajjYearI().getValue());
                haji.setTahunPeruntukan(resp.getTHHajjYear().getValue());
                haji.setPusatKosDeskripsi(resp.getTHOffice().getValue().trim());
                if(resp.getTHRegDate().getValue() != null)
                    haji.setTarikhDaftar(format.parse(resp.getTHRegDate().getValue().trim()));
                THISutil tHISutil = tHISutilDAO.findById("101");  
                haji.setNoTelTHCC(tHISutil.getDeskripsi().toString());
                setHaji(haji); 
                return ("haji/daftarhaji_detail.html");
            }
//            addSimpleError("" + responseManager.getResponseMessage(responseCode, HAJ_CHK_MSG_ID));
            
        } catch (Exception ex) {
            LOG.error(ex);
            responseCode = SYSTEM_ERROR;
            addSimpleError("" + responseManager.getResponseMessage(responseCode, HAJ_CHK_MSG_ID));
        }
        return("/hj_home.html");
    }
    
//----------------------------------------------------CETAK SLIP PENDAFTARAN---------------------------------------------------------//
    
    /**
     *
     * @param haji
     * @param pengguna
     * @param responseCode
     * @param idSessi
     * @return
     */
        
    @AuthRequired
    public String cetakSlipPendaftaran (Haji haji, Pengguna pengguna, String responseCode, String idSessi) {
                  
        SimpleDateFormat d = new SimpleDateFormat("dd/MM/yyyy"); 
        SimpleDateFormat t = new SimpleDateFormat("hh:mm a");
        SejarahTransaksi sejarahTransaksi = new SejarahTransaksi();
        
        try {
            deposit = getProfileDeposit(haji.getNoAkaun(), haji.getNoKp());
        } catch (ParseException ex) {
            java.util.logging.Logger.getLogger(HajiActionBean.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        if (deposit != null) {
            
            AccCheckUtil checking = ableContextListener.newInstance(AccCheckUtil.class);
            deposit.setNoKpDari(haji.getNoKp());
            deposit.setNoAkaunDari(haji.getNoAkaun());
            boolean check = checking.checkAcc(deposit, pengguna);

//            if (!check) {
//               addSimpleError("" + responseManager.getResponseMessage("9000", PROFILE_ENQ_MSG_ID));
//                return new JSP("deposit/msg.jsp");
//            }
//        } else {
//            addSimpleError("" + responseManager.getResponseMessage("9000", PROFILE_ENQ_MSG_ID));
//                return new JSP("deposit/msg.jsp");
//        }
        
            try { // Call Web Service Operation
                com.oas.thit.hajj.services.HajjServices service = new com.oas.thit.hajj.services.HajjServices();
                com.oas.thit.hajj.services.HajjServicesPortType port = service.getHajjServicesHttpSoap11Endpoint();
                // TODO initialize WS operation arguments here
                com.oas.thit.hajj.xsd.Request req = new com.oas.thit.hajj.xsd.Request();                
                
                com.oas.thit.hajj.xsd.ObjectFactory objFactory = new com.oas.thit.hajj.xsd.ObjectFactory();
                com.oas.thit.xmlmessage.xsd.ObjectFactory objHeader = new com.oas.thit.xmlmessage.xsd.ObjectFactory();
                Header reqHead = objHeader.createHeader();
                reqHead.setMsgId( objHeader.createHeaderMsgId(HAJ_SLIP_MSG_ID));
                reqHead.setResponseCode( objHeader.createHeaderResponseCode(SUCCESSFUL) );            
                reqHead.setTxid(objHeader.createHeaderTxid( webUtil.getHeaderID(HAJ_SLIP_MSG_ID, HEADER_ID_HAJ_SLIP_GROUP) ));
                
                JAXBElement<Header> jReqHead = objHeader.createEventHeader(reqHead);
                req.setHeader(jReqHead); 
                
                RequestBody reqBody = objFactory.createRequestBody();
                reqBody.setTHAccountNo(objFactory.createRequestBodyTHAccountNo(haji.getNoAkaun()));
                reqBody.setTHIcNo(objFactory.createRequestBodyTHIcNo(haji.getNoKp()));
                
                JAXBElement<RequestBody> jReqBody =  objFactory.createRequestBody(reqBody);
                req.setBody(jReqBody);
                
                // TODO process result here
                com.oas.thit.hajj.groupslip.xsd.GroupSlipResponse result = port.groupSlip(req);                
                Header header = result.getHeader().getValue();
                responseCode = header.getResponseCode().getValue();
                
                sejarahTransaksi.setPengguna(pengguna);
                sejarahTransaksi.setTrhMasuk(new Date());
                sejarahTransaksi.setUrusan(kodUrusanDAO.findById(HAJ_SLIP_MSG_ID));
                sejarahTransaksi.setIdSessi(getContext().getRequest().getSession().getId());
                sejarahTransaksi.setStatus(kodStatusDAO.findById(responseCode));
                sejarahTransaksi.setNilaiDalaman1(header.getTxid().getValue().trim());                
                    if (responseCode.equals(SUCCESSFUL)) {
                        GroupSlipResponseBody resp = result.getBody().getValue();                        
                        if(resp.getTHHajRefNo().getValue().trim().equals("")){
                            haji.setNoRujukan("Tiada");
                        }else {
                            haji.setNoRujukan(resp.getTHHajRefNo().getValue());
                        }
                        haji.setTahunPeruntukan(resp.getTHHajjYear().getValue());
                        haji.setTahunPeruntukanHijrah(resp.getTHHajjYearI().getValue());
                        DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
                        if(resp.getTHRegDate().getValue() != null)
                            haji.setTarikhDaftar(format.parse(resp.getTHRegDate().getValue()));
                        haji.setNoTelTHCC(resp.getTHOfficePhone().getValue());
                        List<GroupSlipResponseLineItem> items  = resp.getLineItems();
                        List<SlipPendaftaran> senaraiAhli = new ArrayList<SlipPendaftaran>();
                        for ( GroupSlipResponseLineItem item : items ) {
                            SlipPendaftaran sp = new SlipPendaftaran();                        
                            sp.setNama(item.getTHName().getValue());
                            sp.setNoAkaun(item.getTHAcct().getValue());
                            sp.setNoDaftarHaji(item.getTHHajRegNo().getValue());
                            sp.setPejabatPengendali(item.getTHOffice().getValue());                        
                            senaraiAhli.add(sp);
                        }
                        haji.setSenaraiDaftarAhli(senaraiAhli);
                        sejarahTransaksiManager.saveSejarahTransaksi(sejarahTransaksi);
                        getContext().getRequest().getSession().setAttribute("haji", haji);                        
                        return ("haji/cetaklip_detail.html");
                    }
//                    addSimpleError("" + responseManager.getResponseMessage(responseCode, HAJ_SLIP_MSG_ID));            
                } 
                catch (Exception ex) {
                    LOG.error(ex);
                    responseCode = SYSTEM_ERROR;
  //                  addSimpleError("" + responseManager.getResponseMessage(responseCode, HAJ_SLIP_MSG_ID));
                }
            sejarahTransaksiManager.saveSejarahTransaksi(sejarahTransaksi);
            return ("/hj_home.html");
    }   
        return ("/hj_home.html");
    }
//----------------------------------------------------CETAK JADUAL PENERBANGAN-------------------------------------------------------//    
@AuthRequired
    public String cetakJadualPenerbangan(Haji haji, Pengguna pengguna, String responseCode, String idSessi) {

        SejarahTransaksi sejarahTransaksi = new SejarahTransaksi();
        DateFormat format = new SimpleDateFormat("yyyyMMdd");
        
        try {
            deposit = getProfileDeposit(haji.getNoAkaun(), haji.getNoKp());
        } catch (ParseException ex) {
            java.util.logging.Logger.getLogger(HajiActionBean.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        if (deposit != null) {
            
            AccCheckUtil checking = ableContextListener.newInstance(AccCheckUtil.class);
            deposit.setNoKpDari(haji.getNoKp());
            deposit.setNoAkaunDari(haji.getNoAkaun());
            boolean check = checking.checkAcc(deposit, pengguna);

            if (!check) {
                addSimpleError("" + responseManager.getResponseMessage("9000", PROFILE_ENQ_MSG_ID));
  //              return new JSP("deposit/msg.jsp");
            }
        } 
        else {
                addSimpleError("" + responseManager.getResponseMessage("9000", PROFILE_ENQ_MSG_ID));
//                return new JSP("deposit/msg.jsp");
        }
        
        try { // Call Web Service Operation
            com.oas.thit._this.services.THISServices service = new com.oas.thit._this.services.THISServices();
            com.oas.thit._this.services.THISServicesPortType port = service.getTHISServicesHttpSoap11Endpoint();
            // TODO initialize WS operation arguments here
            com.oas.thit._this.xsd.THISRequest req = new com.oas.thit._this.xsd.THISRequest();
            
            com.oas.thit._this.xsd.ObjectFactory objFactory = new com.oas.thit._this.xsd.ObjectFactory();          
            //com.oas.thit.xmlmessage.xsd.ObjectFactory objHeader = new com.oas.thit.xmlmessage.xsd.ObjectFactory();
            
            req.setHeader(webUtil.createHeader(FLT_SCH_MSG_ID, HEADER_ID_HAJ_FLIGHT_SCH) );
            
            //Header reqHead = objHeader.createHeader();
            //reqHead.setMsgId( objHeader.createHeaderMsgId(FLT_SCH_MSG_ID));
            //reqHead.setResponseCode( objHeader.createHeaderResponseCode(SUCCESSFUL) );
            
            //reqHead.setTxid(objHeader.createHeaderTxid( webUtil.getHeaderID(FLT_SCH_MSG_ID, HEADER_ID_HAJ_FLIGHT_SCH) ));
            
            //JAXBElement<Header> jReqHead = objHeader.createEventHeader(reqHead);
            //req.setHeader(jReqHead);            
            
            THISBaseDataElementBody reqBody = objFactory.createTHISBaseDataElementBody();
            reqBody.setTHAcct(objFactory.createTHISBaseDataElementBodyTHAcct(haji.getNoAkaun()));
            reqBody.setTHICNo(objFactory.createTHISBaseDataElementBodyTHICNo(haji.getNoKp()));
            
            JAXBElement<THISBaseDataElementBody> jReqBody =  objFactory.createTHISRequestBody(reqBody);
            req.setBody(jReqBody);  
            
            // TODO process result here
            com.oas.thit._this.flight.xsd.FlightScheduleResponse result = port.hajjFlightSchedule(req);
            
            Header header = result.getHeader().getValue();
            responseCode = header.getResponseCode().getValue();
            
            sejarahTransaksi.setPengguna(pengguna);
            sejarahTransaksi.setTrhMasuk(new Date());
            sejarahTransaksi.setUrusan(kodUrusanDAO.findById(FLT_SCH_MSG_ID));
            sejarahTransaksi.setIdSessi(getContext().getRequest().getSession().getId());
            sejarahTransaksi.setStatus(kodStatusDAO.findById(responseCode));
            sejarahTransaksi.setNilaiDalaman1(header.getTxid().getValue().trim());
            
            if (responseCode.equals(SUCCESSFUL)) {
                FlightScheduleResponseBody resp = result.getBody().getValue();
                
                haji.setNama(resp.getTHName().getValue().trim());
                haji.setNoAkaun(resp.getTHAcct().getValue().trim());
                haji.setNoKp(resp.getTHICNo().getValue().trim());
                haji.setAlamat1(resp.getTHAddress1().getValue().trim());
                haji.setAlamat2(resp.getTHAddress2().getValue().trim());
                haji.setAlamat3(resp.getTHAddress3().getValue().trim());
                haji.setLaporDiriPergi(resp.getTHDepOrigin().getValue().trim());
                
                String laporDiriBalik = resp.getTHRetOrigin().getValue().trim();
                if (laporDiriBalik.equals("JED")) {
                    haji.setLaporDiriBalik("MADINATUL HUJJAJ (JEDDAH )");
                } else if (laporDiriBalik.equals("MED")) {
                    haji.setLaporDiriBalik("LAPANGAN TERBANG (MADINAH )");
                }
                //haji.setLaporDiriBalik(resp.getTHRetOrigin().getValue().trim());
                haji.setCheckInDay(resp.getTHDepCheckinDay().getValue().trim());
                haji.setCheckInPlace(resp.getTHDepCheckinPlace().getValue().trim());
                //haji.setTarikhPergi(format.parse(resp.getTHDepDate().getValue().trim()));
                //haji.setTarikhPergi(format.parse(resp.getTHDepArrivalDate().getValue().trim()));
                haji.setTarikhPergi(format.parse(resp.getTHDepCheckinDate().getValue().trim()));
                haji.setTarikhBalik(format.parse(resp.getTHRetDate().getValue().trim()));
                //add ':' between the time
//                if(resp.getTHDepSTD().getValue()!=null)
//                    haji.setMasaPergi(resp.getTHDepSTD().getValue().substring(0,2).concat(":").concat(resp.getTHDepSTD().getValue().substring(2,4)));                 
//                if(resp.getTHRetSTD().getValue() !=null)
//                    haji.setMasaBalik(resp.getTHRetSTD().getValue().substring(0,2).concat(":").concat(resp.getTHRetSTD().getValue().substring(2,4)));                
//                if(resp.getTHDepSTA().getValue()!=null)    
//                    haji.setMasaTiba1(resp.getTHDepSTA().getValue().substring(0,2).concat(":").concat(resp.getTHRetSTA().getValue().substring(2,4)));
//                if(resp.getTHRetSTA().getValue()!=null)    
//                    haji.setMasaTiba(resp.getTHRetSTA().getValue().substring(0,2).concat(":").concat(resp.getTHRetSTA().getValue().substring(2,4)));
//                if(resp.getTHRetSTA().getValue() !=null)
//                    haji.setWaktuTiba(resp.getTHRetSTA().getValue().substring(0,2).concat(":").concat(resp.getTHRetSTA().getValue().substring(2,4)));

                 /*
                 * Change from 24hrs format to 12hrs with pagi, petang siang, malam
                 */
                
                 SimpleDateFormat datetimeFormatter1 = new SimpleDateFormat("hh:mm");
                 Date a = null;
                 Date b = null;
                 Date c = null;
                 Date d = null;
                 Date e = null;
                 Date f = null;
                 b = datetimeFormatter1.parse("11:59");
                 c = datetimeFormatter1.parse("12:59");
                 d = datetimeFormatter1.parse("18:59");
                 e = datetimeFormatter1.parse("00:00");
                 f = datetimeFormatter1.parse("06:59");
 
                //1
                if(resp.getTHDepSTD().getValue()!= null){
                   String masa = resp.getTHDepSTD().getValue().substring(0,2).concat(":").concat(resp.getTHDepSTD().getValue().substring(2,4)); 
                   //a = datetimeFormatter1.parse(resp.getTHDepSTD().getValue());
                   a = datetimeFormatter1.parse(masa);
                   if (a.compareTo(b) < 0) {
                       masa = masa.concat(" PAGI");
                       haji.setMasaPergi(masa);
                    } else if (a.compareTo(c) < 0) {
                       masa = masa.concat(" TENGAHARI");
                       haji.setMasaPergi(masa);
                    } else if (a.compareTo(d) < 0) {
                       masa = masa.concat(" PETANG");
                       haji.setMasaPergi(masa);
                    } else {
                       
                       //new ADD
                        String[]hm = masa.split(":");
                        int h = Integer.parseInt(hm[0]);
                        int m = Integer.parseInt(hm[1]);
                       int[] hrs = {12,1,2,3,4,5,6,7,8,9,10,11};
                        int time = Integer.parseInt(hm[0]);

                        int hours = hrs[ time % 12 ];
                        int decimalNum = time / 100;
                        decimalNum *= 100;
                        int min = time - decimalNum;

                        System.out.println("The time is: "+ hrs[ time % 12 ] + ":" + m);
                        String newMasa = hrs[ time % 12 ] + ":" + m;
                        newMasa = newMasa.concat(" MALAM");
                       haji.setMasaPergi(newMasa);
                    }
                } else {
                     haji.setMasaPergi(resp.getTHDepSTD().getValue().trim());   
                }
                //2
                //  if(resp.getTHRetSTD().getValue() !=null){
                if(resp.getTHRetCheckinTime().getValue() !=null){
                   String masa = resp.getTHRetCheckinTime().getValue().substring(0,2).concat(":").concat(resp.getTHRetCheckinTime().getValue().substring(2,4)); 
                   //a = datetimeFormatter1.parse(resp.getTHRetSTD().getValue());
                   a = datetimeFormatter1.parse(masa);
                   if (a.compareTo(b) < 0) {
                       masa = masa.concat(" PAGI");
                        haji.setMasaBalik(masa);
                    } else if (a.compareTo(c) < 0) {
                       masa = masa.concat(" TENGAHARI");
                       haji.setMasaBalik(masa);
                    } else if (a.compareTo(d) < 0) {
                       masa = masa.concat(" PETANG");
                       haji.setMasaBalik(masa);
                    } else {
                       //new ADD
                        String[]hm = masa.split(":");
                        int h = Integer.parseInt(hm[0]);
                        int m = Integer.parseInt(hm[1]);
                       int[] hrs = {12,1,2,3,4,5,6,7,8,9,10,11};
                        int time = Integer.parseInt(hm[0]);

                        int hours = hrs[ time % 12 ];
                        int decimalNum = time / 100;
                        decimalNum *= 100;
                        int min = time - decimalNum;

                        System.out.println("Masa Balik :The time is: "+ hrs[ time % 12 ] + ":" + m);
                        String newMasa = hrs[ time % 12 ] + ":" + m;
                        newMasa = newMasa.concat(" MALAM");
                       haji.setMasaBalik(newMasa);
                    }
                } else {
                    haji.setMasaBalik(resp.getTHRetCheckinTime().getValue().trim());
                }
                //3
                if(resp.getTHDepSTA().getValue()!=null){
                   String masa = resp.getTHDepSTA().getValue().substring(0,2).concat(":").concat(resp.getTHDepSTA().getValue().substring(2,4)); 
                   //a = datetimeFormatter1.parse(resp.getTHRetSTD().getValue());
                   a = datetimeFormatter1.parse(masa);
                   if (a.compareTo(b) < 0) {
                       masa = masa.concat(" PAGI");
                       haji.setMasaTiba1(masa);
                    } else if (a.compareTo(c) < 0) {
                       masa = masa.concat(" TENGAHARI");
                       haji.setMasaTiba1(masa);
                    } else if (a.compareTo(d) < 0) {
                       masa = masa.concat(" PETANG");
                       haji.setMasaTiba1(masa);
                    } else {
                      //new ADD
                        String[]hm = masa.split(":");
                        int h = Integer.parseInt(hm[0]);
                        int m = Integer.parseInt(hm[1]);
                       int[] hrs = {12,1,2,3,4,5,6,7,8,9,10,11};
                        int time = Integer.parseInt(hm[0]);

                        int hours = hrs[ time % 12 ];
                        int decimalNum = time / 100;
                        decimalNum *= 100;
                        int min = time - decimalNum;

                        System.out.println("The time is: "+ hrs[ time % 12 ] + ":" + m);
                        String newMasa = hrs[ time % 12 ] + ":" + m;
                        newMasa = newMasa.concat(" MALAM");
                       haji.setMasaTiba1(newMasa);
                    }
                } else {
                    haji.setMasaTiba1(resp.getTHDepSTA().getValue().trim());
                }
                //4
                if(resp.getTHRetSTA().getValue()!=null){
                   String masa = resp.getTHRetSTA().getValue().substring(0,2).concat(":").concat(resp.getTHRetSTA().getValue().substring(2,4)); 
                    //a = datetimeFormatter1.parse(resp.getTHRetSTD().getValue());
                   a = datetimeFormatter1.parse(masa);
                   if (a.compareTo(b) < 0) {
                       masa = masa.concat(" PAGI");
                       haji.setMasaTiba(masa);
                    } else if (a.compareTo(c) < 0) {
                       masa = masa.concat(" TENGAHARI");
                       haji.setMasaTiba(masa);
                    } else if (a.compareTo(d) < 0) {
                       masa = masa.concat(" PETANG");
                       haji.setMasaTiba(masa);
                    } else {
                       //new ADD
                        String[]hm = masa.split(":");
                        int h = Integer.parseInt(hm[0]);
                        int m = Integer.parseInt(hm[1]);
                       int[] hrs = {12,1,2,3,4,5,6,7,8,9,10,11};
                        int time = Integer.parseInt(hm[0]);

                        int hours = hrs[ time % 12 ];
                        int decimalNum = time / 100;
                        decimalNum *= 100;
                        int min = time - decimalNum;

                        System.out.println("The time is: "+ hrs[ time % 12 ] + ":" + m);
                        String newMasa = hrs[ time % 12 ] + ":" + m;
                        newMasa = newMasa.concat(" MALAM");
                       haji.setMasaTiba(newMasa);
                    }
                } else {
                     haji.setMasaTiba(resp.getTHRetSTA().getValue().trim());
                }
                //5
                if(resp.getTHRetSTA().getValue() !=null){
                   String masa = resp.getTHRetSTA().getValue().substring(0,2).concat(":").concat(resp.getTHRetSTA().getValue().substring(2,4));
                    //a = datetimeFormatter1.parse(resp.getTHRetSTD().getValue());
                   a = datetimeFormatter1.parse(masa);
                   if (a.compareTo(b) < 0) {
                       masa = masa.concat(" PAGI");
                       haji.setWaktuTiba(masa);
                    } else if (a.compareTo(c) < 0) {
                       masa = masa.concat(" TENGAHARI");
                       haji.setWaktuTiba(masa);
                    } else if (a.compareTo(d) < 0) {
                       masa = masa.concat(" PETANG");
                       haji.setWaktuTiba(masa);
                    } else {
                       //new ADD
                        String[]hm = masa.split(":");
                        int h = Integer.parseInt(hm[0]);
                        int m = Integer.parseInt(hm[1]);
                       int[] hrs = {12,1,2,3,4,5,6,7,8,9,10,11};
                        int time = Integer.parseInt(hm[0]);

                        int hours = hrs[ time % 12 ];
                        int decimalNum = time / 100;
                        decimalNum *= 100;
                        int min = time - decimalNum;

                        System.out.println("The time is: "+ hrs[ time % 12 ] + ":" + m);
                        String newMasa = hrs[ time % 12 ] + ":" + m;
                        newMasa = newMasa.concat(" MALAM");
                       haji.setWaktuTiba(newMasa);
                    }
                } else {
                    haji.setWaktuTiba(resp.getTHRetSTA().getValue().trim());
                }
                 //6
                //haji.setCheckInTimePhase1(resp.getTHDepCheckinTime().getValue().trim());
                if(resp.getTHDepCheckinTime().getValue() !=null){
                   String masa = resp.getTHDepCheckinTime().getValue().substring(0,2).concat(":").concat(resp.getTHDepCheckinTime().getValue().substring(2,4));
                    //a = datetimeFormatter1.parse(resp.getTHRetSTD().getValue());
                   a = datetimeFormatter1.parse(masa);
                   if (a.compareTo(b) < 0) {
                       masa = masa.concat(" PAGI");
                       
                       if (a.compareTo(f) < 0) {
                            /**
                         * New add : 08082014
                         * Get checkInDate, then minus 1 to handle problem 
                         * waktu melapor diri yg tak lengkap
                         */
                         
                       //Day_OF_WEEK starts from 1 while array index starts from 0
                        String[] strDays = new String[] { "AHAD", "ISNIN", "SELASA", "RABU", "KHAMIS", "JUMAAT", "SABTU" };
                        DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
                        Calendar cal = Calendar.getInstance();
                        
                        cal.setTime(haji.getTarikhPergi());
                        //Subtract one day from current date
                        cal.add(Calendar.DATE, -1);
                        int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);

                        //set
                        String dateMinus = dateFormat.format(cal.getTime());
                        String dayMinus = strDays[dayOfWeek-1];
                        haji.setCheckInDateMinus1(dateMinus);
                        haji.setCheckInDayMinus1(dayMinus);
                        
                        String afterMidnite = "SELEPAS TENGAH MALAM ";
//                        String afterMidniteDetails = null;
//                        String afConcat = dayMinus.concat(dateMinus);
//                        String afConcat2 = afterMidnite.concat(afConcat);
                        //SELEPAS TENGAH MALAM AHAD20140720
                        haji.setAfterMidnite(afterMidnite);
                        System.out.println("Check in date = " + haji.getTarikhPergi());
                        System.out.println("Check in Day = " + haji.getCheckInDay());
                        System.out.println("Day of Checkin day : " + strDays[dayOfWeek]);
                        System.out.println("Day of Checkin date, MINUS  1 : " + haji.getCheckInDateMinus1());
                        System.out.println("Check in Day, minus 1 : " + haji.getCheckInDayMinus1());
                       }
                       haji.setCheckInTimePhase1(masa);
                       
                    } else if (a.compareTo(c) < 0) {
                       masa = masa.concat(" TENGAHARI");
                       haji.setCheckInTimePhase1(masa);
                    } else if (a.compareTo(d) < 0) {
                       masa = masa.concat(" PETANG");
                       haji.setCheckInTimePhase1(masa);
                    }
                    else {
                       //new ADD
                        String[]hm = masa.split(":");
                        int h = Integer.parseInt(hm[0]);
                        int m = Integer.parseInt(hm[1]);
                       int[] hrs = {12,1,2,3,4,5,6,7,8,9,10,11};
                        int time = Integer.parseInt(hm[0]);

                        int hours = hrs[ time % 12 ];
                        int decimalNum = time / 100;
                        decimalNum *= 100;
                        int min = time - decimalNum;

                        System.out.println(" setCheckInTimePhase1 The time is: "+ hrs[ time % 12 ] + ":" + m);
                        String newMasa = hrs[ time % 12 ] + ":" + m;
                        newMasa = newMasa.concat(" MALAM");
                       haji.setCheckInTimePhase1(newMasa);
                    }
                } else {
                    haji.setCheckInTimePhase1(resp.getTHDepCheckinTime().getValue().trim());
                }
 
                
                // ----------- End change 24hrs to 12 hrs  -----------------
                
                
                haji.setNoPesawatPergi(resp.getTHDepFltNo().getValue().trim());
                haji.setNoPesawatBalik(resp.getTHRETFltNo().getValue().trim());
                haji.setJumlahHari(resp.getTHPilgrimDuration().getValue().trim());
                
                String destPergi = resp.getTHDepDestination().getValue().trim();
                if (destPergi.equals("MED")) {
                    haji.setDestinasiPergi("MADINAH");
                } else if (destPergi.equals("JED")) {
                    haji.setDestinasiPergi("JEDDAH");
                }
               // haji.setDestinasiPergi(resp.getTHDepDestination().getValue().trim());
                haji.setMiqatDi(resp.getTHHaramBoundary().getValue().trim());                
                haji.setDestinasiBalik(resp.getTHRetDestination().getValue().trim());
                haji.setDepFinal(resp.getTHDepFinalDest().getValue().trim());
                haji.setRetFinal(resp.getTHRetFinalDest().getValue().trim());
                haji.setNoKt(resp.getTHKTNo().getValue().trim());
                if(resp.getTHPoskod().getValue()!=null){
                        Poskod poskod = poskodDAO.findById(resp.getTHPoskod().getValue().trim());
                        haji.setPoskod( poskod.getPoskod());
                        haji.setPoskodDeskripsi(poskod.getNama());
                    } 
                
                String offAdd1 = resp.getTHOfficeAddress1().getValue().toString().trim();
                String offAdd2 = resp.getTHOfficeAddress2().getValue().toString().trim();
                String offAdd3 = resp.getTHOfficeAddress3().getValue().toString().trim();
              
                if (offAdd1.isEmpty() == false) {
                    offAdd1 = offAdd1.concat(", ");
                }
                if (offAdd2.isEmpty() == false) {
                    offAdd2 = offAdd2.concat(", ");
                }
                if (offAdd3.isEmpty() == false) {
                    offAdd3 = offAdd3.concat(", ");
                }
                haji.setOffAlamat1(offAdd1.concat(offAdd2).concat(offAdd3));
                
                
                //haji.setOffAlamat1(resp.getTHOfficeAddress1().getValue().trim().concat(",").concat(" ").concat(resp.getTHOfficeAddress2().getValue().trim()).concat(",").concat(" ").concat(resp.getTHOfficeAddress3().getValue().trim()).concat(",").concat(" ").concat(resp.getTHOfficeAddress4().getValue().trim()));
                if(resp.getTHOfficePoskod().getValue()!=null){
                        Poskod poskod = poskodDAO.findById(resp.getTHOfficePoskod().getValue().trim());
                        haji.setOffPoskod( poskod.getPoskod());
                        haji.setOffCity(poskod.getNama());
                }
                haji.setOffFax(resp.getTHOfficeFax().getValue().trim());
                haji.setOffPhone(resp.getTHOfficePhone().getValue().trim());
                haji.setGroupRefNo(resp.getTHGroupRefNo().getValue().trim());
                haji.setTahunTawaran(resp.getTHHajYear().getValue().trim());
                haji.setTahunTawaranHijrah(resp.getTHHajYearI().getValue().trim());
                haji.setNoReg(resp.getTHRegNo().getValue().trim());
                haji.setNoPassport(resp.getTHPassportNo().getValue().trim());
                haji.setPakageCode(resp.getTHPackageCode().getValue().trim());
                haji.setHajiOfferStatus(resp.getTHHajOfferStatus().getValue().trim());
                haji.setHajiStatus(resp.getTHHajStatus().getValue().trim());
                haji.setTarikhTiba(format.parse(resp.getTHRetArrivalDate().getValue().trim()));
                haji.setRetCheckinPlace(resp.getTHRetCheckinPlace().getValue().trim());
                haji.setTarikhLaporDiriBalik(format.parse(resp.getTHRetCheckinDate().getValue().trim()));
                
                setHaji(haji); 
                
                SuratPenerbanganJH suratPenerbanganJH = new SuratPenerbanganJH();
                  suratPenerbanganJH.setAcctNo(haji.getNoAkaun());
                  suratPenerbanganJH.setAlamat1(haji.getAlamat1());
                  suratPenerbanganJH.setAlamat2(haji.getAlamat2());
                  suratPenerbanganJH.setAlamat3(haji.getAlamat3());
                  suratPenerbanganJH.setNama(haji.getNama());
                  suratPenerbanganJH.setNoKp(haji.getNoKp());
                  suratPenerbanganJH.setOrigin(haji.getCheckInPlace());
                  suratPenerbanganJH.setReturnDestination(haji.getLaporDiriBalik());
                  suratPenerbanganJH.setCheckInDate(haji.getTarikhPergi());
                  suratPenerbanganJH.setCheckOutDate(haji.getTarikhBalik());
               
                 // suratPenerbanganJH.setCheckInTime(haji.getMasaPergi());
                  suratPenerbanganJH.setCheckInTime(haji.getCheckInTimePhase1());
                  suratPenerbanganJH.setCheckOutTime(haji.getMasaBalik());
                  suratPenerbanganJH.setCheckInDay(haji.getCheckInDay());
                  suratPenerbanganJH.setFlightNo(haji.getNoPesawatPergi());
                  suratPenerbanganJH.setReturnFlightNo(haji.getNoPesawatBalik());
                  
                  String dest = haji.getDepFinal();
                  if (dest.equals("MD")) {
                      suratPenerbanganJH.setDestination("MADINAH");
                  } else if (dest.equals("MK")) {
                      suratPenerbanganJH.setDestination("MEKAH");
                  }
                  //suratPenerbanganJH.setDestination(haji.getDepFinal());
                  
                  suratPenerbanganJH.setAirportTo(haji.getRetFinal());
                  suratPenerbanganJH.setAirportFrom(haji.getRetCheckinPlace());
                  suratPenerbanganJH.setMiqat(haji.getMiqatDi());
                  suratPenerbanganJH.setTotaldays(haji.getJumlahHari());
                  suratPenerbanganJH.setOffAddress(haji.getOffAlamat1().concat(haji.getOffPoskod()).concat(", ").concat(haji.getOffCity()));
                  suratPenerbanganJH.setOffFax(haji.getOffFax());
                  suratPenerbanganJH.setOffPhone(haji.getOffPhone());
                  suratPenerbanganJH.setGroupNo(haji.getGroupRefNo());
                  suratPenerbanganJH.setPackageNo(haji.getPakageCode());
                  suratPenerbanganJH.setKtNo(haji.getNoKt());
                  suratPenerbanganJH.setNormalYear(haji.getTahunTawaran());
                  suratPenerbanganJH.setIslamicYear(haji.getTahunTawaranHijrah());
                  suratPenerbanganJH.setHajiOfferStatus(haji.getHajiOfferStatus());
                  suratPenerbanganJH.setHajiStatus(haji.getHajiStatus());
                  suratPenerbanganJH.setRegNo(haji.getNoReg());
                  suratPenerbanganJH.setPassportNo(haji.getNoPassport());
                  suratPenerbanganJH.setPoskod(haji.getPoskod());
                  suratPenerbanganJH.setNegeri(haji.getPoskodDeskripsi());
                  suratPenerbanganJH.setDateArrived(haji.getTarikhTiba());
                  suratPenerbanganJH.setTimeArrived(haji.getWaktuTiba());
                  suratPenerbanganJH.setRetCheckInDate(haji.getTarikhLaporDiriBalik());
                  //added in 08082014
                  if (haji.getCheckInDateMinus1() != null) {
                      suratPenerbanganJH.setCheckInDateMinus1(haji.getCheckInDateMinus1());
                  } else {
                      suratPenerbanganJH.setCheckInDateMinus1(" ");
                  }
                  
                  if (haji.getCheckInDayMinus1() != null) {
                      suratPenerbanganJH.setCheckInDayMinus1(haji.getCheckInDayMinus1());
                  } else {
                      suratPenerbanganJH.setCheckInDayMinus1(" ");
                  }
                  
                  if (haji.getAfterMidnite() != null) {
                  suratPenerbanganJH.setAfterMidnite(haji.getAfterMidnite());
                  } else {
                      suratPenerbanganJH.setAfterMidnite(" ");
                  }
                  
                  String noKt = haji.getNoKt();
                  suratPenerbanganJH.setNoKT2(noKt.substring(2));
                  
                sejarahTransaksiManager.saveSejarahTransaksi(sejarahTransaksi);
                getContext().getRequest().getSession().setAttribute("SuratPenerbanganJH",suratPenerbanganJH);
                return ("haji/jadualterbang_detail.jsp");               
            }
   //         addSimpleError("" + responseManager.getResponseMessage(responseCode, FLT_SCH_MSG_ID));
        } catch (Exception ex) {            
            LOG.error(ex);
            responseCode = SYSTEM_ERROR;
   //         addSimpleError("" + responseManager.getResponseMessage(responseCode, FLT_SCH_MSG_ID));            
        } 
        sejarahTransaksiManager.saveSejarahTransaksi(sejarahTransaksi);
        return("/hj_home.html");
   
    }
   
    public Deposit getProfileDeposit(String noAkaun, String noKP) throws ParseException {
       
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");

        //Deposit deposit = null;
        
        com.oas.thit._this.services.THISServices service = new com.oas.thit._this.services.THISServices();
        com.oas.thit._this.services.THISServicesPortType port = service.getTHISServicesHttpSoap11Endpoint();
        com.oas.thit._this.xsd.THISRequest reqDeposit = new com.oas.thit._this.xsd.THISRequest();
        com.oas.thit._this.xsd.ObjectFactory objFactoryDeposit = new com.oas.thit._this.xsd.ObjectFactory();
        reqDeposit.setHeader( webUtil.createHeader(PROFILE_ENQ_MSG_ID, HEADER_ID_PROFILE_ENQUIRY) );
        THISBaseDataElementBody reqBodyDeposit = objFactoryDeposit.createTHISBaseDataElementBody();
        
        reqBodyDeposit.setTHAcct(objFactoryDeposit.createTHISBaseDataElementBodyTHAcct(noAkaun));
        reqBodyDeposit.setTHICNo(objFactoryDeposit.createTHISBaseDataElementBodyTHICNo(noKP));

        JAXBElement<THISBaseDataElementBody> jReqBodyDeposit =  objFactoryDeposit.createTHISRequestBody(reqBodyDeposit);
        reqDeposit.setBody(jReqBodyDeposit);
        
         /*
          * Query for deposit : profile
          */
            com.oas.thit._this.profile.depositor.xsd.DepositorProfileResponse resultDeposit = port.depositorProfileQuery(reqDeposit);
            Header headerDeposit = resultDeposit.getHeader().getValue();
            responseCode = headerDeposit.getResponseCode().getValue();
            if (responseCode.equals(SUCCESSFUL)) {
                 DepositorProfileResponseBody respDeposit = resultDeposit.getBody().getValue();
                 if (respDeposit != null) { 
                    deposit = new Deposit();
                    deposit.setAlamat1(respDeposit.getTHAddress1().getValue());
                    deposit.setAlamat2(respDeposit.getTHAddress2().getValue());
                    deposit.setAlamat3(respDeposit.getTHAddress3().getValue());
                    deposit.setBangsa(respDeposit.getTHEthnic().getValue());
                    deposit.setEmail(respDeposit.getTHemail().getValue());
                    deposit.setNoAkaun(respDeposit.getTHAcct().getValue().trim());
                    deposit.setNoBuku(respDeposit.getTHPassbookNo().getValue());
                    deposit.setNoKp(respDeposit.getTHICNo().getValue().trim());
                    deposit.setNoTel1(respDeposit.getTHPhoneHome().getValue());
                    deposit.setNoTel2(respDeposit.getTHPhoneMobile().getValue());
                    deposit.setNoTel3(respDeposit.getTHPhoneOffice().getValue());
                    deposit.setPoskod(respDeposit.getTHPoskod().getValue());
                    deposit.setNama(respDeposit.getTHName().getValue());
                    
                    if (respDeposit.getTHGender() != null) {
                        deposit.setJantina(kodJantinaDAO.findById(respDeposit.getTHGender().getValue().trim()));
                    }
                    if  (respDeposit.getTHMarital() != null) {
                        deposit.setKahwin(kodKahwinDAO.findById(respDeposit.getTHMarital().getValue().trim()));
                    }
                   
                    if (respDeposit.getTHState() != null) {
                        deposit.setNegeri(kodNegeriDAO.findById(respDeposit.getTHState().getValue().trim()));
                    }
                     if (respDeposit.getTHEmploy() != null) {
                        deposit.setPekerjaan(kodPekerjaanDAO.findById(respDeposit.getTHEmploy().getValue().trim()));
                    }
                    if (respDeposit.getTHNationality() != null) {
                        deposit.setWarganegara(kodWarganegaraDAO.findById(respDeposit.getTHNationality().getValue().trim()));
                    }
                    
                    /*
                     * Set date
                     */
                    String df = new DateFormatDetector().getDateFormat(respDeposit.getTHDOB().getValue());
                    sdf = new SimpleDateFormat(df);
                    deposit.setTarikhLahir(sdf.parse(respDeposit.getTHDOB().getValue()));
                    
                 }
            }
        return deposit;
    }
    
    
    public String hajjOfferEnq(
            Haji haji,Pengguna pengguna, String responseCode, String idSessi) {
        
        
        DateFormat d = new SimpleDateFormat("yyyyMMdd");
            com.oas.thit._this.services.THISServices service = new com.oas.thit._this.services.THISServices();
            com.oas.thit._this.services.THISServicesPortType port = service.getTHISServicesHttpSoap12Endpoint();
            // TODO initialize WS operation arguments here
            com.oas.thit._this.xsd.THISRequest req = new com.oas.thit._this.xsd.THISRequest();            
            
            com.oas.thit._this.xsd.ObjectFactory objFactory = new com.oas.thit._this.xsd.ObjectFactory();          
            com.oas.thit.xmlmessage.xsd.ObjectFactory objHeader = new com.oas.thit.xmlmessage.xsd.ObjectFactory();
            Header reqHead = objHeader.createHeader();
            reqHead.setMsgId( objHeader.createHeaderMsgId(HAJ_ENQ_MSG_ID));
            reqHead.setResponseCode( objHeader.createHeaderResponseCode(SUCCESSFUL) );
            
            reqHead.setTxid(objHeader.createHeaderTxid( webUtil.getHeaderID(HAJ_ENQ_MSG_ID, HEADER_ID_HAJ_OFFER_CHECK) ));
            
            JAXBElement<Header> jReqHead = objHeader.createEventHeader(reqHead);
            req.setHeader(jReqHead);            
            
            THISBaseDataElementBody reqBody = objFactory.createTHISBaseDataElementBody();
            reqBody.setTHAcct(objFactory.createTHISBaseDataElementBodyTHAcct(haji.getNoAkaun()));
            reqBody.setTHICNo(objFactory.createTHISBaseDataElementBodyTHICNo(haji.getNoKp()));
            
            JAXBElement<THISBaseDataElementBody> jReqBody =  objFactory.createTHISRequestBody(reqBody);
            req.setBody(jReqBody);  
            
            com.oas.thit._this.hajj.xsd.HajjResponse result = port.hajjCheckOffer(req);
            
            Header header = result.getHeader().getValue();
            responseCode = header.getResponseCode().getValue();
            
            //if (responseCode.equals(SUCCESSFUL) || responseCode.equals(ACCEPTED) || responseCode.equals(DECLINED) || responseCode.equals(CLOSED)) {
            if (responseCode.equals(SUCCESSFUL) || responseCode.equals(ACCEPTED) || responseCode.equals(CLOSED)) {
            try {                
                HajjResponseBody resp = result.getBody().getValue();
                    haji.setNama(resp.getTHName().getValue());
                    haji.setNoAkaun(resp.getTHAcct().getValue());
                    haji.setNoKp(resp.getTHICNo().getValue());
                    haji.setTahunTawaran(resp.getTHYear().getValue());
                    haji.setTahunTawaranHijrah(resp.getTHYearI().getValue());
                    haji.setTarikhTawaran(d.parse(resp.getTHOfferDate().getValue().trim()));
                    haji.setTarikhTutupTawaran(d.parse(resp.getTHCloseDate().getValue().trim()));
                    haji.setStatusHaji(kodStatusHajiDAO.findById(resp.getTHHajjStatus().getValue().toString().trim()));              
                    haji.setPusatKos(pusatKosDAO.findById(resp.getTHOffice().getValue().toString().trim()));
                    if(resp.getTHHajjStatus()!=null && resp.getTHHajjStatus().getValue()!=null){
                        KodStatus kodStatus = (kodStatusDAO.findById(resp.getTHHajjStatus().getValue().trim()));
                        haji.setStatusTawaran(kodStatus.getNama());
                    }                    
                    THISutil tHISutil = tHISutilDAO.findById("101");  
                    haji.setNoTelTHCC(tHISutil.getDeskripsi().toString());
                    setHaji(haji);
                    
//                    if (haji.getStatusHaji() == null) {
//                       //  return new JSP("haji/pertanyaan_tawaran_haji_detail.jsp");
//                    } else if (haji.getStatusHaji().getKod().equalsIgnoreCase("G")) {
//                       // addSimpleMessage("TUAN / PUAN TELAH MENOLAK TAWARAN");
//                       // return new JSP("haji/msg.jsp");
//                    } 
                    
//                    
//                    if (haji.getStatusHaji().getKod().equalsIgnoreCase("G")) {
//                        addSimpleMessage("TUAN / PUAN TELAH MENOLAK TAWARAN");
//                        return new JSP("haji/msg.jsp");
//                    } else {
//                        return new JSP("haji/pertanyaan_tawaran_haji_detail.jsp");
//                    }
                    
                   //return new JSP("haji/pertanyaan_tawaran_haji_detail.jsp");
            } catch (ParseException ex) {
                java.util.logging.Logger.getLogger(HajiService.class.getName()).log(Level.SEVERE, null, ex);
            } catch (Exception ex) {
            LOG.error(ex);
            responseCode = SYSTEM_ERROR;
            addSimpleError("" + responseManager.getResponseMessage(responseCode, HAJ_ENQ_MSG_ID)); 
        }

   

        
            } else if (responseCode.equals(DECLINED)) {
                 addSimpleMessage("TUAN / PUAN SUDAH MENOLAK TAWARAN"); 
            } else if (responseCode.equals(DECLINED_G)) {
                addSimpleMessage("TUAN / PUAN TELAH MENOLAK TAWARAN");
            }else {addSimpleError("" + responseManager.getResponseMessage(responseCode, HAJ_ENQ_MSG_ID));
            

    }            
        

   return responseCode;
    }    
    
    @Override
    public ableActionBeanContext getContext() {
        return (ableActionBeanContext) super.getContext();
    }   

    public String getUserId() {
        if(getContext() != null)
            if(getContext().getCurrentUser() != null)
                return getContext().getCurrentUser().getIdPengguna();
        return "ADMIN";
    }
    
    public String getCounter() {
        if (getContext() != null) {
            if (!"".equals(getContext().getCounter()) && getContext().getCounter()!= null) {
                 return getContext().getCounter();
            }
        }
        return "";
    }
    
    public Pengguna getPengguna() {
        return pengguna;
    }

    public void setPengguna(Pengguna pengguna) {
        this.pengguna = pengguna;
    }
    
    public Haji getHaji() {
        return haji;
    }

    public void setHaji(Haji haji) {
        this.haji = haji;
    }
    
}
